package algotithm.leetcode.listnode.jianzhi22;

import algotithm.leetcode.listnode.ListNode;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/18-9:27
 * @URL https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
 * @Title 剑指 Offer 22. 链表中倒数第k个节点
 */
public class Solution {

    public static void main(String[] args) {
        ListNode node1 =  new ListNode(1);
        ListNode node2 =  new ListNode(2);
        ListNode node3 =  new ListNode(3);
        ListNode node4 =  new ListNode(4);
        ListNode node5 =  new ListNode(5);
        int k = 2;

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        Solution solution = new Solution();
        ListNode kthFromEnd = solution.getKthFromEnd(node1, k);
        while (kthFromEnd != null) {
            System.out.print(kthFromEnd.val + " ");
            kthFromEnd = kthFromEnd.next;
        }
    }

    public ListNode getKthFromEnd(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        ListNode first = head;
        ListNode second = head;
        while (k-- > 0 && first != null) {
            first = first.next;
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        return second;
    }

}
